package com.quanyan.factory;



import com.quanyan.api.CmdInterface;
import com.quanyan.entity.Command;
import com.quanyan.entity.ParamStruct;

import java.lang.reflect.Constructor;
import java.util.HashMap;

public class CommandFactory {
    public static final String COMMAND_PREFIX = "com.quanyan.api.";
    
    public static final String COMMAND_POSTFIX = "Command";
    
    public static HashMap<String, Constructor<?>> commandHashMap = new HashMap<String, Constructor<?>>(); // 缓存
    
    public static CmdInterface create(ParamStruct paramStruct) {
        Command commandData=paramStruct.getCommand();
        String cmdStr=commandData.getCmd();
        String[] cmdArr=cmdStr.split("#");
        int cmd=Integer.parseInt(cmdArr[0]);
        CmdInterface command = null;
        try {
            String cmdCommand="";
            switch (cmd) {
                case 1:
                    cmdCommand = "HeartBeat";
                    break;
                case 2:
                    cmdCommand = "Business";
                    break;
            }
            
            String clazzName = COMMAND_PREFIX + cmdCommand +  COMMAND_POSTFIX;
            Constructor<?> constructor = commandHashMap.get(clazzName);
            if (constructor != null) {
                command = (CmdInterface)constructor.newInstance(paramStruct);
                return command;
            }
            Class<?> clazz = Class.forName(clazzName);
            Class<?>[] paramTypes = new Class[] {ParamStruct.class};
            Object[] param = new Object[] {paramStruct};
            constructor = clazz.getDeclaredConstructor(paramTypes);
            commandHashMap.put(clazzName, constructor);
            command = (CmdInterface)constructor.newInstance(param);
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch (NoSuchMethodException ne) {
            ne.printStackTrace();
        }
        catch (SecurityException se) {
            se.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return command;
    }
}
